<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/4/12
 * Time: 10:45
 */

namespace Admin\Frontend\Controllers;


use Admin\Ims\Controllers\ProductController;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolSite;
use Admin\Models\user\XhsysUser;
use Helpers\Assets;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Services\ConfigManage;

class SchoolSiteController extends ControllerBase
{

    private static $enums = [
        'bLong' => [1 => '永久', 2 => '实时'],
        'bShow' => [1 => '是', 2 => '否']
    ];


    /**
     * 检查类型
     *
     * @param string $operate
     * @return bool
     *
     * create by dale 20180327
     */
    public function checkPower($operate = '')
    {
        $tag = 'App_WebSite';
        if ($operate != '') {
            $tag .= '_'.ucfirst($operate); //首字母大写
        }
        return UserPower::checkUserPower($tag);
    }

    /**
     * 错误信息
     *
     * @param bool $isView
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|string
     *
     * create by dale 20180327
     */
    public function sendPowerMsg($isView = false)
    {
        if ($isView) {
            return $this->sendViewError('没有权限');
        } else {
            return $this->sendErrorResponse(401, '缺少权限');
        }
    }

    /**
     * 站点列表
     *
     * @return \Phalcon\Mvc\View
     *
     * create by dale 20180412
     */
    public function siteListAction()
    {

        Assets::easyUI();
        Assets::importJs('js/school_site/siteList.js');
        $this->view->pick('school_site/siteList');
        Template::exists('Coop_Info', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
        $listButtonArr = $formButtonArr = $listSearchArr = array();
        if ($this->checkPower('add')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_add', 'text' => '新增', 'icon' => 'fa-plus');
        }
        if ($this->checkPower('del')) {
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
        }
        $schools = XhschoolInfo::getSchoolSupportArray(true);
        $schools[''] = '请选择学校';
        if (!User::isAdmin()) {
            $user = XhsysUser::findFirst(Main::getLoginUserInfo('userId'));
            if ($user && $user->iSchoolId) {
                $schoolId = $user->iSchoolId;
            }
        } else {
            $schoolId = 2747;
        }
        $listSearchArr[] = array('type' => 'select', 'id' => 'select_school', 'data' => $schools,
            'default' => $schoolId, 'style' => 'width:200px;');
        $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
            'icon' => 'fa-search', 'style' => 'margin-left:10px' );
        return $this->view->setVars([
            'List'       => Template::createList('list', 'School_Site', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'schoolId'   => $schoolId,
        ]);
    }

    /**
     * 获取站点信息
     *
     * create by dale 20180412
     * modify by fyh 20181210
     */
    public function getSiteAction()
    {
        if (!$this->checkPower()) {
            return $this->sendPowerMsg();
        }
        $schoolId = $this->request->getPost('schoolId', 'int');
        $userId   = $this->request->getPost('userId', 'int');
        $key      = $this->request->getPost('key', 'string');
        $order    = $this->request->getPost('order', 'string');
        $sort     = $this->request->getPost('sort', 'string');
        try {
            $configManage = new ConfigManage();
            $data = $configManage->schoolSiteGetSite($schoolId, $userId, $key, $order, $sort);
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


    /**
     * 站点表单
     * create by dale 20180412
     */
    public function siteFormAction($iSSId = null)
    {
        $this->view->pick('school_site/siteForm');
        Assets::select2();
        Assets::datetimePicker();
        Assets::importJs('js/school_site/siteForm.js');
        try {
            $data = ConfigManage::schoolSiteSiteForm($iSSId);
            $this->view->setVar('schoolId', $data['schoolId']);
            $this->view->setVar('schools', $data['schools']);
            $this->view->setVars($data['webArr']);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存站点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180412
     * modify by dale 20180917 添加图片上传
     * modify by fyh 20181210
     */
    public function saveSiteAction()
    {
        $data = $this->request->getPost();
        try {
            $fullPath = '';
            if ($this->request->hasFiles()) { //有图片上传
                $file = $this->request->getUploadedFiles()[0];
                $fileName = $file->getName();
                if ($fileName) {
                    $fullPath = TEMP_PATH . $fileName;
                    if (!is_writable(TEMP_PATH)) {
                        return $this->sendErrorResponse(500, TEMP_PATH . '缓存无写入权限');
                    }
                    $file->moveTo($fullPath);
                }
            }
            ConfigManage::schoolSiteSaveSite($data, $fullPath);
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }



    /**
     * 删除站点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180412
     * modify by fyh 20181210
     */
    public function delSiteAction()
    {
        $id = $this->request->getPost('id');
        if (!$id) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            ConfigManage::schoolSiteDelSite($id);
            return $this->sendSuccessResponse('删除成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }
}